'use strict'

const Controller = require('egg').Controller
const Joi = require('@hapi/joi')
const _ = require('lodash')
const uuidv4 = require('uuid/v4')
const moment = require('moment')
const urlencode = require('urlencode')
const OSS = require('ali-oss')

class OssController extends Controller {
  async GetOssPostObjectParams() {
    const { ctx, app } = this
    const ossConfig = app.config.aliyun.oss
    const MpUploadOssHelper = app.lib.uploadOssHelper
    try {
      const joi_schema = Joi.object().keys({
        path: Joi.string().default(''),
        bucket: Joi.string().default('fspsxh-data-secret'),
      })
      const joi_validate = joi_schema.validate(ctx.request.body)
      if (joi_validate.error) {
        ctx.invalid(joi_validate.error)
        return
      }
      const params = joi_validate.value
      const mpHelper = new MpUploadOssHelper({
        accessKeyId: ossConfig.accessKeyId,
        accessKeySecret: ossConfig.accessKeySecret,
        timeout: 1, // 限制参数的生效时间(单位：小时)。
        maxSize: 10, // 限制上传文件大小(单位：Mb)。
      })
      // 生成参数。
      const ossParams = mpHelper.createUploadParams()

      const timestamp = uuidv4()
      const middlePath = params.path ? `${params.path}` : ''

      ossParams.fileName = `${middlePath}/${timestamp}`
      ossParams.host = `https://${params.bucket}.oss-cn-guangzhou.aliyuncs.com`

      ctx.success(ossParams)
    } catch (err) {
      ctx.fail(err)
    }
  }

  async GetOssUrl() {
    const { ctx, service } = this
    const { oss } = service.utils

    // 字段验证
    const joiSchema = Joi.object({
      oss_path: Joi.string().required(),
      expires: Joi.number().integer().default(3600),
      width: Joi.number().integer().default(1024),
    })
    const validResult = joiSchema.validate(ctx.request.body)
    if (validResult.error) {
      ctx.invalid(validResult.error)
      return
    }
    const params = validResult.value

    try {
      const getConfig = _.pick(params, ['expires', 'width'])

      const newUrl = oss.getUrl(params.oss_path, getConfig)
      ctx.success({
        ...params,
        url: newUrl,
      })
    } catch (err) {
      ctx.fail(err)
    }
  }

  /**
   * 识别接口：
   */
  async LicenseOcrOfUrl() {
    const { ctx, app } = this
    const ossConfig = app.config.aliyun.oss

    try {
      const params = ctx.joi({
        oss_path: Joi.string(),
        oss_type: Joi.string(), // id1Path id2Path // licensePath
        app_name: Joi.string(),
        bucket: Joi.string().default('fspsxh-data-secret'),
      })

      const { region, ossUrlPrefix, newUrlPrefix } =
        ossConfig.bucket[params.bucket]

      const client = new OSS({
        region,
        accessKeyId: ossConfig.accessKeyId,
        accessKeySecret: ossConfig.accessKeySecret,
        bucket: params.bucket,
      })

      const url = client.signatureUrl(params.oss_path, {
        expires: 3600,
        process: 'image/resize,w_1024',
      })

      const imgUrl = url.replace(ossUrlPrefix, newUrlPrefix)
      console.log('imgUrl', imgUrl)

      let resBody = {
        // type: params.oss_type === 'id1Path' ? 'Front' : 'Back',
        // name: '萨达莱',
        // id: '440603199404119321',
      }
      if (['id1Path', 'id2Path', 'licensePath'].includes(params.oss_type)) {
        resBody = await this.WechatLicenseOcr(imgUrl, params.oss_type)
      }

      const apiRes = {
        ...resBody, // 转换车辆类型
        license_img: null,
        oss_path: params.oss_path,
      }

      ctx.success(apiRes)
    } catch (err) {
      ctx.fail(err)
    }
  }

  /**
   * 微信证件识别
   */
  async WechatLicenseOcr(imgUrl, ossType) {
    const { app, service } = this
    const { wechatApi } = service

    const appName = 'mina_rider'

    imgUrl = urlencode(imgUrl, 'utf8')

    let res = null

    if (ossType === 'licensePath') {
      res = await wechatApi.ocrOfUrlOfPrintedText(appName, imgUrl)
      if (!res.items) throw '识别失败'
      let isLicense = false
      let carNum = ''
      res.items.forEach(item => {
        if (item.text === '广东省电动自行车行驶证') isLicense = true
        const carNunIndex = item.text.indexOf('号牌号码')
        if (carNunIndex > -1) {
          carNum = item.text
            .substr(carNunIndex)
            .split('号牌号码')[1]
            .substr(0, 8)
        }
      })
      if (!isLicense) throw '请识别正确证件'
      res.car_num = carNum
    } else {
      res = await wechatApi.ocrOfUrlOfIdCard(appName, imgUrl)
    }

    if (!res) throw '识别失败'

    console.log('微信识别直接返回结果', res)
    if (res.errcode !== 0 || res.errmsg !== 'ok') throw '证件识别失败'

    return res
  }
}

module.exports = OssController
